import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, InsertFnType, IToolbarConfig } from '@wangeditor/editor';
import { useState, useEffect } from 'react';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { useCallback } from 'react';

export default (props) => {
  const { value, onChange, ...other } = props;
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  const [html, setHtml] = useState(value);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/api/upload',
        name: 'file',
        customInsert(res: any, insertFn: InsertFnType) {
          const { code, data } = res;
          if (code === 0 && data) {
            const { url, alt, href } = data;
            insertFn(`/api/upload/${url}`, alt, href);
          }
        },
      },
      uploadVideo: {
        server: '/api/upload',
        customInsert(res: any, insertFn: InsertFnType) {
          const { code, data } = res;
          if (code === 0 && data) {
            const { url, alt, href } = data;
            insertFn(`/api/upload/${url}`, alt, href);
          }
        },
      },
    },
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  const _onChange = useCallback((editor) => {
    const html = editor.getHtml();
    setHtml(editor.getHtml());
    onChange?.(html);
  }, []);

  return (
    <>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={_onChange}
        mode="default"
        style={{ height: '500px', overflowY: 'hidden' }}
      />
    </>
  );
};
